from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from utils.encrypt import md5
import uuid
import os


@csrf_exempt
def UploadView(request):
    if request.method == "POST":
        images = request.FILES.get('data', None)
        if not images:
            return JsonResponse({'status': False, 'msg': "请上传图片"})
        images_suffix = images.name.split(".")[-1]  # 获取后缀
        files_name = md5(str(uuid.uuid4())) + '.' + images_suffix
        with open(os.path.join(settings.STATICFILES_DIRS[0], files_name), 'wb') as f:
            f.write(images.read())
        return JsonResponse({'status': True, "msg": files_name})
    if request.method == "GET":
        files_name = request.GET.get('images')
        dirs = os.path.join(settings.STATICFILES_DIRS[0], files_name)
        os.remove(dirs)
        return JsonResponse({'status': True, 'msg': "删除成功"})

    return JsonResponse({'status': False, 'msg': "没有当前请求"})
